package KK.Time
{
	import KK.System.Pool.Pool;
	
	import flash.utils.getTimer;
	
	public class S_Timer extends Pool
	{
		static public const OFF_TIME:int=-1;//时间未到 
		static public const ON_TIME:int=0;//时间到了
		
		private var count:uint;//次数
		private var timer:uint;//时间
		private var Complete:Function;//完成时回调 
		private var params:Array;//回调参数
		private var currentCount:uint;//当前调用次数
		private var nExcutionTime:uint;//执行时间
		
		public function S_Timer()
		{
			//TODO: implement function
			super();
			reset();
		}
		
		/**
		 * 检查是否时间到达 
		 * @return 
		 * 
		 */
		public function CheckTimeout():int{
			var result:int=OFF_TIME;
			var timeout:Boolean=(getTimer()-nExcutionTime)>=timer;
			if(count>currentCount&&timeout){
				if(this.params){
					this.Complete.apply(this,this.params);
				}else{
					this.Complete();
				}
				nExcutionTime=getTimer();
				if(count!=0xFFFFFFFF){
					currentCount++;
				}
			}
			if(currentCount>=count){
				Remove();
			}
			return result;
		}
		
		/**
		 * 设置超时执行 
		 * @param timer
		 * @param Complete
		 * @param params
		 * 
		 */
		public function setTimeout(Complete:Function,timer:uint,...params):void{
			var arr:Array=[Complete,timer,1];
			arr=arr.concat(params);
			this.setTimer.apply(this,arr);
		}
		/**
		 * 设置定时器 
		 * @param time
		 * @param count
		 * @param Complete
		 * @param params
		 * 
		 */
		public function setTimer(Complete:Function,timer:uint,count:uint=0xFFFFFFFF,...params):void{
			this.timer=timer;
			this.count=count;
			this.Complete=Complete;
			if(params.length>0){
				this.params=params;
			}else{
				this.params=null;
			}
			this.nExcutionTime=getTimer();
			
		}
		/**
		 * 移除定时器 
		 * 
		 */
		public function Remove():void{
			reset();
			UnUsed();
		}
		
		/**
		 * 重置  
		 * 
		 */
		public function reset():void{
			count=0;
			timer=0;
			currentCount=0;
			nExcutionTime=0;
			params=null;
			Complete=null;
		}
	}
}